﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
namespace Skynet.Office
{
    public  class ExcelUtility
    {
        public static void CreateExcelAndSave(string name)
        {
            //var excel = new Excel.Application();
            //excel.Visible = true;
            //Workbook workBook = excel.Workbooks.Add();
            //excel.Cells[1, 1].Font.FontStyle = "Bold";
            //excel.Cells[1, 1].Value2 = "Hello World";
            //workBook.SaveAs(@"temp.xlsx");

            var missing = System.Reflection.Missing.Value;
            var excel = new Excel.Application();
            excel.Visible = true;
            Workbook workBook = excel.Workbooks.Add(missing);
            var range = (Excel.Range)excel.Cells[1, 1];
            range.Font.FontStyle = "Bold";
            range.Value2 = "Hello world";
            workBook.SaveAs(@"d:\temp.xlsx", missing, missing, missing, missing,
            missing, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing,
            missing, missing, missing);
 
        }
        public static void  CreateExcelDynamic(string name)
        {
            Type excelAppType = Type.GetTypeFromProgID("Excel.Application", true);
            dynamic excel = Activator.CreateInstance(excelAppType);
            excel.Visible = true;
            dynamic wb = excel.Workbooks.Add();
            excel.Cells[1, 1].Value2 = "foo";
        }
        public static object CreateExcel(string name)
        {
            Excel.Application x1 = new Excel.Application();
            x1.Visible = true;
            Excel.Workbook wb = x1.Workbooks.Add(Excel.XlSheetType.xlWorksheet);

            Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
            Excel.Range r = (Excel.Range)ws.Cells[1, "A"];
            r.Value2 = "Hello World";
            return x1;
            
        }
        public static void ReleaseExcel(object exc)
        {
            var app = exc as Excel.Application;

            if (app != null )
            {
                app.Quit();
                app = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();                
            }
        }
    }
}
